package com.atguigu.gulimall.ware.listener;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.mq.OrderTo;
import com.atguigu.common.to.mq.StockDetailTo;
import com.atguigu.common.to.mq.StockLockedTo;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.atguigu.gulimall.ware.entity.WareOrderTaskEntity;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.atguigu.gulimall.ware.vo.OrderVo;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
@RabbitListener(queues = "stock.release.stock.queue")
public class StockReleaseListener {

    @Autowired
    WareSkuService wareSkuService;
   /*gl:  如下两个方法会根据传递来的消息类型处理不同类型的消息*/
    /**
     * 监听解锁库存 只要解锁库存的消息失败，一定要告诉服务解锁失败
     */
    @RabbitHandler  //C297
    public void handleStockLockedRelease(StockLockedTo to, Message message, Channel channel) throws IOException {
        System.out.println("收到解锁库存的消息");
        try {
            wareSkuService.unlockStock(to); // 根据库存任务对象to来解锁库存
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }

    /*  根据ordersn找到找到其商品对应的"库存订单任务表" 将之前商品扣除补回来
     ordersn-->wareordertaskID-->找到WareOrderTaskDetailEntity（每一条工作单）将商品数量改回去-->*/
    @RabbitHandler  //C299-26:20  这个是收到的消息是来自 定时自动关单的
    public void handleOrderCloseRelease(OrderTo orderTo,Message message,Channel channel) throws IOException {
        System.out.println("订单关闭，准备解锁库存....");
        try {
            wareSkuService.unlockStock(orderTo);// 根据订单对象orderTo解锁库存
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }
}
